package com.zyf.project.binaryproto.encoder.impl;

import com.zyf.project.binaryproto.converter.DynamicValueConverter;
import com.zyf.project.binaryproto.converter.impl.AbstractNumberEncodingConverter;
import com.zyf.project.binaryproto.specification.BinarySliceSpecification;
import com.zyf.project.binaryproto.specification.FieldSpecification;
import org.jetbrains.annotations.NotNull;
import utils.binary.BytesSlices;
import utils.binary.impl.BytesSlice;
import utils.binary.impl.DynamicBytesSliceArray;
import utils.binary.io.BytesInputStream;
import utils.binary.io.BytesOutputBuffer;
import utils.io.NumberMask;

import java.lang.reflect.Array;
import java.lang.reflect.Method;

/**
 * <h1>动态数组编码器</h1>
 * <p>所谓动态就是可变长</p>
 * <p>继承了 {@link AbstractFieldEncoder}</p>
 *
 * @author Zhou Yifan
 */
public class DynamicArrayFieldEncoder extends AbstractFieldEncoder {

    protected DynamicValueConverter valueConverter;

    private NumberMask numberMask;

    public DynamicArrayFieldEncoder(
            BinarySliceSpecification binarySliceSpecification,
            FieldSpecification fieldSpecification,
            Method reader,
            DynamicValueConverter valueConverter) {
        super(binarySliceSpecification, fieldSpecification, reader);
        this.valueConverter = valueConverter;
        if (valueConverter instanceof AbstractNumberEncodingConverter) {
            numberMask = ((AbstractNumberEncodingConverter) valueConverter).getNumberMask();
        }
    }

    /**
     * 将数据序列化到指定缓存中
     *
     * @param dataContract 数据
     * @param buffer       指定缓存 {@link BytesOutputBuffer}
     * @return 写入的字节数
     */
    @Override
    public int encode(Object dataContract, BytesOutputBuffer buffer) {
        int size = 0;
        Object values = readValue(dataContract);
        size += encodeArrayDynamic(values, buffer);
        return size;
    }

    /**
     * 对数组类型的值进行非固定长度的编码
     *
     * @param values 待编码数据
     * @param buffer 目标缓存区
     * @return 写入字符数
     */
    protected int encodeArrayDynamic(Object values, @NotNull BytesOutputBuffer buffer) {
        int size = 0;

        int count = values == null ? 0 : Array.getLength(values);
        byte[] countBytes = NumberMask.NORMAL.generateMask(count);
        buffer.write(countBytes);
        size += countBytes.length;

        for (int i = 0; i < count; i++) {
            size += valueConverter.encode(Array.get(values, i), buffer);
        }

        return size;
    }

    /**
     * 将 BytesInputStream 反序列化成数据片
     *
     * @param bytesInputStream {@link BytesInputStream}
     * @return {@link BytesSlices}
     */
    @Override
    public BytesSlices decode(BytesInputStream bytesInputStream) {
        if (numberMask != null) {
            return DynamicBytesSliceArray.resolveNumbers(numberMask, bytesInputStream);
        } else {
            return DynamicBytesSliceArray.resolve(bytesInputStream);
        }
    }

    /**
     * 字段解码
     *
     * @param fieldBytes 一组相关联的数据片段 {@link BytesSlices}
     * @return 对象 {@link Object}
     */
    @Override
    public Object decodeField(BytesSlices fieldBytes) {
        if (fieldBytes == null) {
            throw new IllegalArgumentException("FieldBytes is null!");
        }
        int fieldCount = fieldBytes.getCount();
        Object[] values;
        if (null != valueConverter.getArrayConstructor()) {
            values = (Object[]) valueConverter.getArrayConstructor().apply(fieldCount);
        } else {
            values = (Object[]) Array.newInstance(valueConverter.getValueType(), fieldCount);
        }
        BytesSlice itemSlice;
        for (int i = 0; i < fieldCount; i++) {
            itemSlice = fieldBytes.getDataSlice(i);
            if (itemSlice.getSize() == 0) {
                values[i] = valueConverter.getDefaultValue();
            } else {
                values[i] = valueConverter.decode(itemSlice);
            }
        }
        return values;
    }
}
